package com.tju.backend.plugin.common;

import cn.hutool.core.util.HexUtil;
import cn.hutool.json.JSONUtil;
import com.tju.backend.plugin.t_io_server.SPServerAioListener;
import com.tju.backend.plugin.web_socket.TioMsgHandler;
import com.tju.backend.utils.hex.HexStringUtil;
import com.tju.backend.utils.result.ResultEnum;
import com.tju.backend.utils.result.ResultUtil;
import com.tju.backend.utils.tool.Constants;
import lombok.extern.slf4j.Slf4j;
import org.tio.core.Tio;
import org.tio.websocket.common.WsResponse;

import java.util.Arrays;
import java.util.Optional;

/**
 * TCP推送数据
 *
 * @Author CLS
 * @Date 2021/11/4 11:33
 */
@Slf4j
public class Push {

    /**
     * WebSocket推送数据处理
     *
     * @param msg
     */
    public static void push(Object msg) {
        WsResponse wsResponse = WsResponse.fromText(JSONUtil.parse(msg).toString(), Const.CHARSET);
        Optional.ofNullable(TioMsgHandler.channelContext)
                .map(o -> {
                    Tio.sendToGroup(TioMsgHandler.channelContext.tioConfig, Const.GROUP_NAME, wsResponse);
                    return Constants.STRING;
                });
    }

    /**
     * TCP/IP服务端推送数据
     *
     * @param msg
     */
    public static void tcpPush(String msg) {
        Optional.ofNullable(SPServerAioListener.channelContext)
                .map(o -> {
                    SPPacket packet = new SPPacket();
                    packet.setBody(HexUtil.decodeHex("FFFF" + msg + "EE"));
                    Tio.sendToGroup(SPServerAioListener.channelContext.tioConfig, Const.GROUP_NAME, packet);
                    return Constants.STRING;
                });

    }

    /**
     * TCP/IP服务端推送数据
     *
     * @param msg
     */
    public static void msgPush(String msg) {
        Optional.ofNullable(SPServerAioListener.channelContext)
                .map(o -> {
                    SPPacket packet = new SPPacket();
                    packet.setBody(HexUtil.decodeHex(msg));
                    Tio.sendToGroup(SPServerAioListener.channelContext.tioConfig, Const.GROUP_NAME, packet);
                    return Constants.STRING;
                });

    }
}
